package com.github.iot.activity;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.KeyEvent;
import android.widget.ImageView;

import com.github.iot.R;
import com.github.iot.utils.ActivityUtils;
import com.github.iot.utils.SharedPreferencesUtils;

import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import butterknife.ButterKnife;
import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;

/**
 * 欢迎页 Activity
 *
 * @Author: 梁声洪
 * @Date: 2019/12/06 9:57
 * @Version: v1.0.0
 */
public class WelcomeActivity extends Activity {

    @BindView(R.id.iv_entry)
    ImageView mEntry;

    private static final int ANIM_TIME = 3000;
    private static final float SCALE_END = 1.15F;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // 判断是否是第一次开启应用
        boolean isFirstOpen = SharedPreferencesUtils.getBoolean(this, "first_open", true);
        if (isFirstOpen) {
            Intent intent = new Intent(this, WelcomeGuideActivity.class);
            startActivity(intent);
            finish();
            return;
        }

        setContentView(R.layout.activity_welcome);
        ButterKnife.bind(this);
        startMainActivity();
    }

    private void startMainActivity() {
        Observable.timer(100, TimeUnit.MILLISECONDS)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(t -> startAnim());
    }

    private void startAnim() {
        ObjectAnimator animatorX = ObjectAnimator.ofFloat(mEntry, "scaleX", 1f, SCALE_END);
        ObjectAnimator animatorY = ObjectAnimator.ofFloat(mEntry, "scaleY", 1f, SCALE_END);

        AnimatorSet set = new AnimatorSet();
        set.setDuration(ANIM_TIME).play(animatorX).with(animatorY);
        set.start();

        set.addListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationEnd(Animator animation) {
                String user = SharedPreferencesUtils.getString(WelcomeActivity.this, "iot_login_user", null);
                if (null == user) {
                    ActivityUtils.skipActivityAndFinishAll(WelcomeActivity.this, LoginActivity.class);
                } else {
                    ActivityUtils.skipActivityAndFinishAll(WelcomeActivity.this, MainActivity.class);
                }
            }
        });
    }

    /**
     * 屏蔽物理返回按钮
     *
     * @param keyCode
     * @param event
     * @return
     */
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

}